﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace YouDaoNotesCodes
{
    class selfDefine3Section:ConfigurationSection
    {
        #region 自定义配置文件读取-方式3：CDATA
        [ConfigurationProperty("T1", IsRequired = true)]
        public MyTextElement T1
        {
            get { return (MyTextElement)this["T1"]; }
        }

        [ConfigurationProperty("T2", IsRequired = true)]
        public MyTextElement T2
        {
            get { return (MyTextElement)this["T2"]; }
        }
        public class MyTextElement : ConfigurationElement
        {
            protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
            {
                CommandText = reader.ReadElementContentAs(typeof(string), null) as string;
            }
            protected override bool SerializeElement(XmlWriter writer, bool serializeCollectionKey)
            {
                if (writer != null)
                    writer.WriteCData(CommandText);
                return true;
            }

            [ConfigurationProperty("data", IsRequired = false)]
            public string CommandText
            {
                get { return this["data"].ToString(); }
                set { this["data"] = value; }
            }
        }
        //方式3调用
        public void readSelfDefine3()
        {
            selfDefine3Section se3 = (selfDefine3Section)ConfigurationManager.GetSection("selfDefine3");
            string strT1 = se3.T1.CommandText.Trim();
            Console.Write(strT1);
            Console.ReadKey();
        }
        #endregion

        //方式3调用
        public void getSectionByCDATA()
        {
            selfDefine3Section se3 = (selfDefine3Section)ConfigurationManager.GetSection("selfDefine3");
            Console.Write(se3.T1.CommandText.Trim());
            Console.ReadKey();
        }

        #region 自定义配置文件写入-方式3
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        public void writeSectionByCDATA()
        {
            selfDefine3Section section3 = config.GetSection("selfDefine3") as selfDefine3Section;
            section3.T1.CommandText = "";
            section3.T2.CommandText = "";
            config.Save();
        }
        #endregion
    }
}
